package org.kettle.scheduler.system.biz.component;

import org.apache.commons.lang3.StringUtils;
import org.kettle.scheduler.system.api.enums.LogLevelEnum;
import org.kettle.scheduler.system.api.enums.RunTypeEnum;
import org.kettle.scheduler.system.api.request.TransReq;
import org.kettle.scheduler.system.biz.mq.bo.TransTask;
import org.kettle.scheduler.system.biz.service.SysTransService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;

import lombok.extern.slf4j.Slf4j;

/**
 * 描述:
 *
 * @author xieyonggao
 */
@Slf4j
@Component
public class TopicTransReceiver {

	@Autowired
	private SysTransService transService;

	@RabbitListener(queues = "kettleTaskNewQueue") // 监听的队列名称 kettleTransQueue
	@RabbitHandler
	public void newTrans(Message message) {
		log.debug("TopicTransDoneReceiver消费者收到消息  : " + new String(message.getBody()));
		String messageString = new String(message.getBody());
		if (StringUtils.isEmpty(messageString))
			return;

		TransTask transTask = JSONObject.parseObject(messageString, TransTask.class);
		if (!validationTask(transTask))
			return;

		TransReq req = new TransReq();
		req.setTransType(RunTypeEnum.REP.getCode());
		req.setTransRepositoryId(1);

		Integer categoryId = transTask.getCategoryId();
		if (null == categoryId) categoryId = 1; // 默认分类ID
		req.setTransPath(transTask.getTransPath());
		req.setTransParams(transTask.getTransParams());
		req.setTransName(transTask.getTransName());
		req.setTransQuartz(transTask.getTransQuartz() == null ? 1 : transTask.getTransQuartz());
		req.setSyncStrategy(transTask.getSyncStrategy());
		req.setTransLogLevel(StringUtils.isEmpty(transTask.getTransLogLevel()) ? LogLevelEnum.BASIC.getCode()
				: transTask.getTransLogLevel());
		req.setCategoryId(categoryId);

		Integer id = transService.add(req);
		
		transService.startTrans(id);
		log.debug("DirectTransReceiver消费者收到消息  : " + JSONObject.toJSONString(transTask));
	}
	
	private boolean validationTask(TransTask transTask) {
		if (StringUtils.isEmpty(transTask.getTransName())) {
			log.error("TransName is empty");
			return false;
		}
		if (StringUtils.isEmpty(transTask.getTransPath())) {
			log.error("TransPath is empty");
			return false;
		}

		return true;
	}
}
